import os
import sys
import logging
import logging.handlers

from limber import documents
from limber import views
from limber import viewdisplayers

PLATFORM = sys.platform
WIN_PLATFORM = 'win' in PLATFORM
UNIX_PLATFORM = 'linux' in PLATFORM or 'darwin' in PLATFORM
LINUX_PLATFORM = 'linux' in PLATFORM
MAC_PLATFORM = 'darwin' in PLATFORM

DEBUG=True


def create_userdir(path):
    '''Create the userdirectory.'''

    comps_dir = os.path.join(path, 'Components')
    widgets_dir = os.path.join(path, 'Widgets')

    if not os.path.exists(comps_dir):
        os.makedirs(os.path.join(path, 'Components'))
    if not os.path.exists(widgets_dir):
        os.makedirs(os.path.join(path, 'Widgets'))

    components_fnames_and_contents = (
        documents.COMPONENTS_FNAMES_AND_CONTENTS +
        views.COMPONENTS_FNAMES_AND_CONTENTS +
        viewdisplayers.COMPONENTS_FNAMES_AND_CONTENTS)

    for name, content in components_fnames_and_contents:
        if not os.path.isabs(name):
            name = os.path.join(path, name)
        fil = open(name, 'w')
        fil.write(content)
        fil.close()

    widgets_fnames_and_linknames = (
        documents.WIDGETS_FNAMES_AND_LINKNAMES +
        views.WIDGETS_FNAMES_AND_LINKNAMES +
        viewdisplayers.WIDGETS_FNAMES_AND_LINKNAMES)

    for name, symname in widgets_fnames_and_linknames:
        if not os.path.isabs(symname):
            symname = os.path.join(path, symname)

        os.symlink(name, symname)

create_systemdir = create_userdir

if not os.path.exists(os.path.expanduser('~/.limber')):
    LOG_FILENAME = os.path.expanduser('~/.limberlog')
else:
    LOG_FILENAME = os.path.expanduser('~/.limber/log')

limber_logger = logging.getLogger('limber')
limber_logger.setLevel(logging.DEBUG)

limber_formatter = logging.Formatter('%(asctime)s - %(name)s: %(levelname)s - %(message)s')
limber_file_handler = logging.handlers.RotatingFileHandler(LOG_FILENAME,
                                                           maxBytes=102400,
                                                           backupCount=10)
limber_file_handler.setLevel(logging.DEBUG)

limber_stream_handler = logging.StreamHandler()
if DEBUG:
    limber_stream_handler.setLevel(logging.DEBUG)
else:
    limber_stream_handler.setLevel(logging.WARNING)

limber_file_handler.setFormatter(limber_formatter)
limber_stream_handler.setFormatter(limber_formatter)

limber_logger.addHandler(limber_file_handler)
limber_logger.addHandler(limber_stream_handler)


def log(msg, level='DEBUG',logger=limber_logger):
    '''Logs a message to the root logger.

    *level* defaults to "DEBUG".
    *logger* default to the limber logger.
    '''

    levels = (
        'NOTSET',
        'DEBUG',
        'INFO',
        'WARNING',
        'ERROR',
        'CRITICAL')

    if level not in levels:
        for lev, val in ((l, getattr(loggin,l)) for l in levels):
            if val == level:
                break
        else:
            raise ValueError('Invalid level: %r.' % level)

        level = lev

    logger_func = getattr(logger, level.lower())
    logger_func(msg)

def debug(msg, logger=limber_logger):
    '''Logs a message to *logger* using the DEBUG level.

    *logger* defaults to *limber_logger*.
    '''

    log(msg, 'DEBUG', logger)

def info(msg, logger=limber_logger):
    '''Logs a message to *logger* using the INFO level.

    *logger* default to *limber_logger*.
    '''

    log(msg, 'INFO', logger)

def warning(msg, logger=limber_logger):
    '''Logs a message to *logger* using the WARNING level.

    *logger* default to *limber_logger*.
    '''

    log(msg, 'WARNING', logger)

def error(msg, logger=limber_logger):
    '''Logs a message to *logger* using the ERROR level.

    *logger* default to *limber_logger*.
    '''

    log(msg, 'ERROR', logger)

def critical(msg, logger=limber_logger):
    '''Logs a message to *logger* using the CRITICAL level.

    *logger* default to *limber_logger*.
    '''

    log(msg, 'CRITICAL', logger)
